package com.tcxhb.job.core.schedule;

import com.tcxhb.job.core.entity.JobRunDTO;
import com.tcxhb.job.core.schedule.execute.JobRunExecutor;
import com.tcxhb.job.dao.dataobject.JobInfoDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @Description: 时间片轮询
 * @Auther: tcxhb
 * @Date: 2023/11/7
 */
@Component
@Slf4j
public class JobWaitScheduler implements Scheduler {
    private BlockingDeque<JobInfoDO> waitQueue = new LinkedBlockingDeque<>();
    @Autowired
    private JobRunExecutor jobRunExecutor;

    public Set<String> waitSet = new ConcurrentSkipListSet<>();

    @PostConstruct
    @Override
    public void start() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                scan();
            }
        });
        thread.setDaemon(true);
        thread.start();
    }

    /**
     * 轮询
     */
    public void scan() {
        while (true) {
            try {
                Long now = System.currentTimeMillis();
                JobInfoDO jobDO = waitQueue.take();
                waitSet.remove(jobDO.uniqId());
                if (now >= jobDO.getNextTime()) {
                    JobRunDTO jobRun = new JobRunDTO(jobDO.getId(), jobDO.getNextTime());
                    jobRunExecutor.run(jobRun);
                } else {
                    //一直循环
                    submit(jobDO);
                }
            } catch (Exception e) {
                log.error("scanWaitQueue exception", e);
            }
        }
    }

    public void submit(JobInfoDO job) {
        try {
            String uniqId = job.uniqId();
            if (waitSet.contains(uniqId)) {
                return;
            }
            waitQueue.offer(job);
            waitSet.add(job.uniqId());
        } catch (Exception e) {
            log.error("offer job exception:" + job.getId(), e);
        }
    }
}
